var request = require('superagent'),
  config = require('./config');

module.exports = function parseVerifyCode(opt){

  // 获取验证码 get the verifycode
  request.get(config.HOST + config.PATH)
    .query({
      uin: opt.qq,
      appid: config.APPID,
      ptlang: config.PTLANG,
      r: Math.random()
    })
    .buffer() //这里的响应类型为x-javascript，不属于 text/* 和 application/json，强制响应为简单字符串
    .end(function(res){

      var cookies, i, len,
        verifycode,
        verifycodeReg = /,\'.*,\'/,
        cookieReg = /PATH=(.*);|DOMAIN=(.*);/;

      if(res.ok){

        //构造cookie，保留使用
        cookies = res.header['set-cookie'];
        for(i=0,len=cookies.length;i<len;i++){
          cookies[i] = cookies[i].replace(cookieReg, '');
        };

        cookies = cookies.join('');
        cookies = cookies.substring(0, cookies.lastIndexOf(';'));

        //获取验证码
        verifycode = res.text.match(verifycodeReg);
        verifycode = verifycode[0].split("'")[1];

        if(verifycode.length > 4){//需要图片验证码
          opt.backData.cap_cd = verifycode;

          console.log('verifycode error : ' + res.text);
        };

        opt.backData.verifycode = verifycode;
        opt.backData.cookies = cookies;

      }else{
        opt.backData.errorMsg = res.text;
      };

      if(typeof opt.callback == 'function'){
        opt.callback();
      };

    });
};